package com.uziot.bucket.rest.template.config;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

/**
 * 功能描述: <br>
 * RestTemplate 配置类
 *
 * @author shidt
 * @date 2019-08-19 22:47
 */
@Configuration
public class RestTemplateConfig {
    /**
     * 请求拦截器
     *
     * @return RestTemplateInterceptor
     */
    @Bean
    @ConditionalOnMissingBean
    public RestTemplateInterceptor restTemplateInterceptor() {
        return new RestTemplateInterceptor();
    }

    @Primary
    @Bean
    public RestTemplate restTemplate(RestTemplateInterceptor restTemplateInterceptor) {
        HttpClient httpClient = HttpClientBuilder.create()
                .setRedirectStrategy(new LaxRedirectStrategy()).build();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectionRequestTimeout(30 * 1000);
        factory.setConnectTimeout(30 * 3000);
        factory.setReadTimeout(30 * 3000);
        factory.setHttpClient(httpClient);

        RestTemplate restTemplate = new RestTemplate(factory);
        // 设置全局请求拦截器
        restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor));
        return restTemplate;
    }

}
